//
//  StreamingManager.swift
//  replaykit
//
//  Created by zhang on 2025/7/31.
//

import Foundation
import CoreMedia
import CoreVideo

class StreamingManager: NSObject {
    
    // MARK: - Properties
    private let videoEncoder: VideoEncoder
    private let rtmpConnection: RTMPConnection
    
    private var isStreaming = false
    private var frameCount = 0
    
    // 配置
    private let rtmpURL: String
    private let streamName: String
    
    // 回调
    var onStreamingStatusChanged: ((Bool) -> Void)?
    var onError: ((String) -> Void)?
    
    // MARK: - Initialization
    init(rtmpURL: String, streamName: String) {
        self.rtmpURL = rtmpURL
        self.streamName = streamName
        
        // 初始化组件
        self.videoEncoder = VideoEncoder(width: 1280, height: 720, fps: 30, bitrate: 2000000)
        self.rtmpConnection = RTMPConnection(url: rtmpURL, streamName: streamName)
        
        super.init()
        
        setupCallbacks()
    }
    
    deinit {
        stopStreaming()
    }
    
    // MARK: - Setup
    private func setupCallbacks() {
        // 视频编码器回调
        videoEncoder.onEncodedData = { [weak self] h264Data, timestamp in
            self?.rtmpConnection.sendVideoPacket(h264Data, timestamp: timestamp)
        }
        
        videoEncoder.onError = { [weak self] (error: String) in
            print("StreamingManager: 视频编码错误: \(error)")
            self?.onError?(error)
        }
        
        // RTMP连接回调
        rtmpConnection.onConnectionStatusChanged = { [weak self] connected in
            print("StreamingManager: RTMP连接状态: \(connected)")
        }
        
        rtmpConnection.onPublishStatusChanged = { [weak self] publishing in
            print("StreamingManager: RTMP推流状态: \(publishing)")
        }
        
        rtmpConnection.onError = { [weak self] error in
            print("StreamingManager: RTMP错误: \(error)")
            self?.onError?(error)
        }
    }
    
    // MARK: - Streaming Control
    func startStreaming() -> Bool {
        print("StreamingManager: 开始推流")
        print("StreamingManager: 目标URL: \(rtmpURL)")
        print("StreamingManager: 流名称: \(streamName)")
        
        // 1. 设置视频编码器
        print("StreamingManager: 步骤1 - 设置视频编码器...")
        guard videoEncoder.setupEncoder() else {
            print("StreamingManager: ❌ 视频编码器设置失败")
            onError?("视频编码器设置失败")
            return false
        }
        print("StreamingManager: ✅ 视频编码器设置成功")
        
        // 2. 连接RTMP服务器
        print("StreamingManager: 步骤2 - 连接RTMP服务器...")
        guard rtmpConnection.connect() else {
            print("StreamingManager: ❌ RTMP连接失败")
            onError?("RTMP连接失败")
            return false
        }
        print("StreamingManager: ✅ RTMP连接成功")
        
        // 3. 异步等待连接完成后再开始推流
        DispatchQueue.global(qos: .background).async { [weak self] in
            print("StreamingManager: 等待RTMP连接完成...")
            
            // 等待连接完成（最多等待3秒）
            let startTime = Date()
            while !(self?.rtmpConnection.getConnectionStatus() ?? false) && Date().timeIntervalSince(startTime) < 3.0 {
                Thread.sleep(forTimeInterval: 0.1)
            }
            
            guard let self = self else { return }
            
            if self.rtmpConnection.getConnectionStatus() {
                print("StreamingManager: RTMP连接已就绪，开始推流...")
                
                // 开始推流
                guard self.rtmpConnection.startPublishing() else {
                    print("StreamingManager: ❌ RTMP推流开始失败")
                    DispatchQueue.main.async {
                        self.onError?("RTMP推流开始失败")
                    }
                    return
                }
                
                DispatchQueue.main.async {
                    self.isStreaming = true
                    self.frameCount = 0
                    self.onStreamingStatusChanged?(true)
                    print("StreamingManager: ✅ 推流开始成功")
                }
            } else {
                print("StreamingManager: ❌ RTMP连接超时")
                DispatchQueue.main.async {
                    self.onError?("RTMP连接超时")
                }
            }
        }
        
        return true
    }
    
    func stopStreaming() {
        print("StreamingManager: 停止推流")
        
        // 停止视频编码器
        videoEncoder.stopEncoder()
        
        // 停止RTMP推流
        rtmpConnection.stopPublishing()
        
        // 断开RTMP连接
        rtmpConnection.disconnect()
        
        isStreaming = false
        onStreamingStatusChanged?(false)
        
        print("StreamingManager: 推流已停止")
    }
    
    // MARK: - Video Frame Processing
    func processVideoFrame(_ pixelBuffer: CVPixelBuffer) {
        guard isStreaming else { 
            print("StreamingManager: 跳过视频帧处理 - 推流未开始")
            return 
        }
        
        frameCount += 1
        
        // 获取像素缓冲区信息
        let width = CVPixelBufferGetWidth(pixelBuffer)
        let height = CVPixelBufferGetHeight(pixelBuffer)
        
        // 创建时间戳
        let timestamp = CMTime(value: CMTimeValue(frameCount), timescale: CMTimeScale(30)) // 30fps
        
        // 编码视频帧
        videoEncoder.encodeFrame(pixelBuffer, timestamp: timestamp)
        
        // 每100帧打印一次状态
        if frameCount % 100 == 0 {
            print("StreamingManager: 已处理 \(frameCount) 帧 - 分辨率: \(width)x\(height)")
        }
        
        // 前几帧打印详细信息
        if frameCount <= 5 {
            print("StreamingManager: 处理第 \(frameCount) 帧 - 分辨率: \(width)x\(height)")
        }
    }
    
    // MARK: - Status
    func getStreamingStatus() -> Bool {
        return isStreaming
    }
    
    func getFrameCount() -> Int {
        return frameCount
    }
} 